﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;

namespace Function
{
    public class Method
    {
        /// <summary>
        /// 网站前缀
        /// </summary>
        private static string m_SitePrefix = (ConfigurationManager.AppSettings["SitePrefix"] == null) ? "WebSiteDonet" : ConfigurationManager.AppSettings["SitePrefix"].ToString();

        /// <summary>
        /// 网站前缀
        /// </summary>
        public static string SitePrefix
        {
            get
            {
                return m_SitePrefix;
            }
        }

        public const string Aeskey = "5dCJ]kfU#x3j4JPr";
        public const string AesVector = "Qz#5y]tUV@NFMu6v";

        public const string Deskey = "WJ#@Zd68";

        #region 加解密
        /// <summary>
        /// des加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Encode(string data)
        {
            return Encode(data, Deskey);
        }

        /// <summary>
        /// des解密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Decode(string data)
        {
            return Decode(data, Deskey);
        }

        /// <summary>
        /// des加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Encode(string data, string key)
        {
            byte[] byKey = Encoding.Default.GetBytes(key);
            byte[] byIV = Encoding.Default.GetBytes(key);
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            cryptoProvider.Mode = CipherMode.ECB;
            cryptoProvider.Padding = PaddingMode.Zeros;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();

            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
        }

        /// <summary>
        /// des解密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Decode(string data, string key)
        {
            byte[] byKey = Encoding.Default.GetBytes(key);
            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            cryptoProvider.Mode = CipherMode.ECB;
            cryptoProvider.Padding = PaddingMode.Zeros;
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byKey), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
        #endregion

        #region 调接口
        /// <summary>
        /// 接口地址
        /// </summary>
        public enum InterfaceConnection
        {
            /// <summary>
            /// php添加/编辑商品品牌接口
            /// </summary>
            phpAddOrEditBrand = 0,

            /// <summary>
            /// 获取token
            /// </summary>
            phpToken = 1,

            /// <summary>
            /// php删除品牌接口
            /// </summary>
            phpDelBrand = 2,

            /// <summary>
            /// 获取商品分类
            /// </summary>
            phpGetGoodsType = 3,

            /// <summary>
            /// 通用商品信息编辑(标签1)
            /// </summary>
            phpEditGoods = 4,

            /// <summary>
            /// 获取通用信息
            /// </summary>
            phpGetGoodsInfo = 5,

            /// <summary>
            /// 获取商品属性
            /// </summary>
            phpGetGoodsProperty = 6,

            /// <summary>
            /// 商品属性设置
            /// </summary>
            phpSetGoodsProperty = 7,

            /// <summary>
            /// 同步商品相册
            /// </summary>
            phpAddGoodsPicture = 8,

            /// <summary>
            /// 获取关联商品
            /// </summary>
            phpGetLinkGoods = 9,

            /// <summary>
            /// 设置关联商品
            /// </summary>
            phpSetLinkGoods = 10,
            /// <summary>
            /// 新增会员
            /// </summary>
            phpaddMember = 11,
            /// <summary>
            /// 新增/修改 活动商量列表信息
            /// </summary>
            phpeditPlanGoods = 12
        }


        /// <summary>
        /// 得到接口地址
        /// </summary>
        /// <param name="con"></param>
        /// <returns></returns>
        public static string GetInterfaceUrl(InterfaceConnection con)
        {
            string url = string.Empty;
            switch (con)
            {
                case InterfaceConnection.phpGetLinkGoods:
                    url = Method.AppSettings("phpGetLinkGoods");
                    break;
                case InterfaceConnection.phpSetLinkGoods:
                    url = Method.AppSettings("phpSetLinkGoods");
                    break;
                case InterfaceConnection.phpAddOrEditBrand:
                    url = Method.AppSettings("phpAddBrand");
                    break;
                case InterfaceConnection.phpDelBrand:
                    url = Method.AppSettings("phpDelBrand");
                    break;
                case InterfaceConnection.phpToken:
                    url = Method.AppSettings("phpToken");
                    break;
                case InterfaceConnection.phpGetGoodsType:
                    url = Method.AppSettings("phpGetGoodsType");
                    break;
                case InterfaceConnection.phpEditGoods:
                    url = Method.AppSettings("phpEditGoods");
                    break;
                case InterfaceConnection.phpGetGoodsInfo:
                    url = Method.AppSettings("phpGetGoodsInfo");
                    break;
                case InterfaceConnection.phpGetGoodsProperty:
                    url = Method.AppSettings("phpGetGoodsProperty");
                    break;
                case InterfaceConnection.phpSetGoodsProperty:
                    url = Method.AppSettings("phpSetGoodsProperty");
                    break;
                case InterfaceConnection.phpAddGoodsPicture:
                    url = Method.AppSettings("phpAddGoodsPicture");
                    break;
                case InterfaceConnection.phpaddMember:
                    url = Method.AppSettings("phpaddMember");
                    break;
                case InterfaceConnection.phpeditPlanGoods:
                    url = Method.AppSettings("phpeditPlanGoods");
                    break;
            }
            return url;
        }
        /// <summary>
        /// 循环替换特殊符号
        /// </summary>
        /// <param name="StrValues"></param>
        /// <returns></returns>
        public static string GetReplaceValue(string StrValues)
        {
            string str = "";
            string[] oldwords = { "=" };
            string[] newwords = { "⇔" };
            for (int i = 0; i < oldwords.Length; i++)
            {
                str = StrValues.Replace(oldwords[i], newwords[i]);
            }
            return str;
        }

        /// <summary>
        /// 得到接口返回的数据
        /// </summary>
        /// <param name="transferData">namevaluecollect的数据</param>
        /// <param name="con">接口链接</param>
        /// <param name="keyStr">数据字符串 con=</param>
        /// <returns></returns>
        public static string GetInterfaceString(string transferData, InterfaceConnection con, string keyStr = "con", bool aesDecrypt = true, bool replace = true)
        {
            if (transferData.IsEmpty())
                throw new ArgumentNullException();
            transferData = transferData.AesEncrypt();
            string returnStr = string.Empty;
            string url = GetInterfaceUrl(con);
            using (WebClient client = new WebClient())
            {
                NameValueCollection col = new NameValueCollection();
                col.Add(keyStr, transferData);
                returnStr = client.UploadValues(url, col).ToByteString();
            }
            if (aesDecrypt)
            {
                try
                {
                    var temp = returnStr;
                    temp = returnStr.AesDecrypt(replace: replace);
                    returnStr = temp;
                }
                catch (FormatException)
                {
                    try
                    {
                        returnStr = returnStr.subFirstChar().AesDecrypt(replace: replace);
                    }
                    catch (Exception)
                    {
                        try
                        {
                            returnStr = returnStr.subFirstChar().subFirstChar().AesDecrypt(replace: replace);
                        }
                        catch (Exception)
                        {

                            returnStr = returnStr.subFirstChar().subFirstChar().subFirstChar().AesDecrypt(replace: replace);
                        }
                    }
                }
            }
            return returnStr.Trim();
        }

        /// <summary>
        /// 得到接口并json转换成指定类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="con"></param>
        /// <returns></returns>
        public static T GetInterfaceString<T>(InterfaceConnection con, string transferData = "", bool aesDecrypt = true, bool replace = true) where T : class
        {
            T returnValue = null;
            string returnStr = string.Empty;
            if (transferData == "")
            {
                returnStr = GetInterfaceString(con, aesDecrypt: false);
            }
            else
            {
                returnStr = GetInterfaceString(transferData, con, aesDecrypt: false);
            }
            if (aesDecrypt)
            {
                try
                {
                    var temp = returnStr;
                    temp = returnStr.AesDecrypt(replace: replace);
                    returnStr = temp;
                }
                catch (FormatException)
                {
                    try
                    {
                        returnStr = returnStr.subFirstChar().AesDecrypt(replace: replace);
                    }
                    catch (Exception)
                    {
                        try
                        {
                            returnStr = returnStr.subFirstChar().subFirstChar().AesDecrypt(replace: replace);
                        }
                        catch (Exception)
                        {

                            returnStr = returnStr.subFirstChar().subFirstChar().subFirstChar().AesDecrypt(replace: replace);
                        }
                    }
                }
            }
            returnValue = JsonDeserialize<T>(returnStr);
            return returnValue;
        }

        /// <summary>
        /// 接受接口返回的普通字符串 未自动解密
        /// </summary>
        /// <param name="con"></param>
        /// <returns></returns>
        public static string GetInterfaceString(InterfaceConnection con, bool aesDecrypt = false, bool replace = false)
        {
            string returnStr = string.Empty;
            string url = GetInterfaceUrl(con);
            using (WebClient client = new WebClient())
            {
                returnStr = client.DownloadString(url);
            }
            if (aesDecrypt)
            {
                try
                {
                    var temp = returnStr;
                    temp = returnStr.AesDecrypt(replace: replace);
                    returnStr = temp;
                }
                catch (FormatException)
                {
                    try
                    {
                        returnStr = returnStr.subFirstChar().AesDecrypt(replace: replace);
                    }
                    catch (Exception)
                    {
                        try
                        {
                            returnStr = returnStr.subFirstChar().subFirstChar().AesDecrypt(replace: replace);
                        }
                        catch (Exception)
                        {

                            returnStr = returnStr.subFirstChar().subFirstChar().subFirstChar().AesDecrypt(replace: replace);
                        }
                    }
                }
            }
            return returnStr.Trim();
        }

        /// <summary>
        /// JSON序列化
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }


        #endregion

        /// <summary>
        /// 生成订单
        /// </summary>
        /// <param name="startpart">开始部分 一般用于辨识何种订单</param>
        /// <param name="id">主键</param>
        /// <param name="sublength">截取长度 默认6位</param>
        /// <param name="padChar">id长度不足截取长度时填充字符 默认0</param>
        /// <param name="subYear">是否截取年前2位</param>
        /// <returns></returns>
        public static string GenerateCode(string startpart, int id, int sublength = 6, char padChar = '0')
        {
            var code = id.ToString();
            //如果大于6位则截取最后6位
            if (code.ToString().Length > sublength)
            {
                code = code.ToString().Substring(code.ToString().Length - sublength);
            }
            else
                code = id.ToString(new string(padChar, sublength));
            return startpart + code;
        }

        /// <summary>
        /// 生成通用单子编码(年月日yyyyMMdd)+2位编码定义+4位id
        /// </summary>
        /// <param name="middlePart">定义部分</param>
        /// <param name="id">id</param>
        /// <param name="sublength">截取长度 默认4</param>
        /// <param name="padChar">填充字符 0</param>
        /// <returns></returns>
        public static string GenerateCommonCode(string middlePart, int id, int sublength = 4, char padChar = '0')
        {
            var code = id.ToString();
            //如果截取位数则截取最后的指定位数
            if (code.ToString().Length > sublength)
            {
                code = code.ToString().Substring(code.ToString().Length - sublength);
            }
            else
                code = id.ToString(new string(padChar, sublength));
            return DateTime.Now.ToString("yyyyMMdd") + middlePart + code;
        }
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="content"></param>
        public static void WriteFile(string fileName, string content)
        {
            StreamWriter writer = new StreamWriter(fileName, true);
            writer.WriteLine(content);
            writer.Close();
        }
        /// <summary>
        /// 生成门店/仓库/经销商的编码
        /// </summary>
        /// <param name="region"></param>
        /// <param name="entityCode"></param>
        /// <param name="id"></param>
        /// <param name="sublength"></param>
        /// <param name="padChar"></param>
        /// <returns></returns>
        public static string GenerateEntityShop(string region, string entityCode, int id, int sublength = 4, char padChar = '0')
        {
            var code = id.ToString();
            //如果截取位数则截取最后的指定位数
            if (code.ToString().Length > sublength)
            {
                code = code.ToString().Substring(code.ToString().Length - sublength);
            }
            else
                code = id.ToString(new string(padChar, sublength));
            return region + entityCode + code;
        }

        /// <summary>
        /// 当前时间 19位
        /// </summary>
        public static string CurrentTime
        {
            get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }
        }

        /// <summary>
        /// 生成当前时间戳
        /// </summary>
        /// <returns>当前时间戳</returns>
        public static string UNIX()
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return timeStamp;
        }

        /// <summary>
        /// 生成指定时间戳的时间戳
        /// </summary>
        /// <param name="StrStamp">指定的时间戳</param>
        /// <returns>时间戳</returns>
        public static string UNIX(string StrStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = Convert.ToDateTime(StrStamp);
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return timeStamp;
        }

        /// <summary>
        /// 时间戳转换为完整时间(yyyy-MM-dd)
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns></returns>
        public static string UNIXStr(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 时间戳转换为指定格式时间 默认(yyyy-MM-dd)
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns></returns>
        public static string UNIXStr(string timeStamp, string format)
        {
            if (string.IsNullOrEmpty(format)) { format = "yyyy-MM-dd"; }
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult.ToString(format);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        public static void SignIn(string username)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    username,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(200),
                    true,
                    "",
                    FormsAuthentication.FormsCookiePath
                    );
            string key = FormsAuthentication.Encrypt(ticket); //得到加密后的身份验证票字串 

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, key);
            //cookie.Domain = System.Web.Security.FormsAuthentication.CookieDomain;  // 这句话在部署网站后有用，此为关系到同一个域名下面的多个站点是否能共享Cookie
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 得到第一张图片的路径
        /// </summary>
        /// <param name="objStr"></param>
        /// <returns></returns>
        public static string GetFirstImagePath(string objStr)
        {
            string returnStr = "";
            //取得image标签
            MatchCollection ml = Regex.Matches(objStr, "<img .*? />");
            foreach (Match m in ml)
            {
                string str = m.Value;
                //取得取得src
                MatchCollection ml2 = Regex.Matches(str, "src=\".*?\"");
                foreach (Match item in ml2)
                {
                    returnStr = item.Value.Split('=')[1];
                    break;
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 得到第一张图片img标签
        /// </summary>
        /// <param name="objStr"></param>
        /// <returns></returns>
        public static string GetFirstImageLabel(string objStr)
        {
            string returnStr = "";
            //取得image标签
            MatchCollection ml = Regex.Matches(objStr, "<img .*? />");
            foreach (Match m in ml)
            {
                returnStr = m.Value;
            }
            return returnStr;
        }

        /// <summary>
        /// 当前页面路径
        /// </summary>
        public static string GetScriptName
        {
            get
            {
                return HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString();
            }
        }

        /// <summary>
        /// Get the url of the current page
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetHomeBaseUrl(string fileName)
        {
            string getScriptName = GetScriptName;
            return string.Format("{0}/{1}", getScriptName.Remove(getScriptName.LastIndexOf("/")), fileName);
        }

        public static string ParaListUrl
        {
            get
            {
                return GetHomeBaseUrl("list.aspx?mid=" + HttpContext.Current.Request.QueryString["mid"] ?? "0" + "&PageIndex=" + HttpContext.Current.Request.QueryString["PageIndex"] ?? "1");
            }
        }

        public static string ParaListUrl1(string url)
        {
            return GetHomeBaseUrl(url.Trim() + "?mid=" + HttpContext.Current.Request.QueryString["mid"] ?? "0" + "&PageIndex=" + HttpContext.Current.Request.QueryString["PageIndex"] ?? "1");
        }
        /// <summary>
        /// 得到相对目录深度
        /// </summary>
        public static string RelativePathDepth
        {
            get
            {
                var count = (GetScriptName.Where(s => s == '/').Count() - 1);
                var str = "";
                for (int i = 0; i < count; i++)
                {
                    str += "../";
                }
                return str;
            }
        }

        /// <summary>
        /// 当前域
        /// </summary>
        public static string GetDamain
        {
            get
            {
                return "http://" + HttpContext.Current.Request.Url.Authority + "/";
            }
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height)
        {
            Image img = Image.FromFile(originalImagePath);
            Image b = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(() => false), IntPtr.Zero);
            b.Save(thumbnailPath);
            img.Dispose();
            b.Dispose();
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }


        /// <summary>
        /// 如果目录不存在 则创建目录
        /// </summary>
        /// <param name="dir"></param>
        public static void CreateDirectory(string dir)
        {
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
        }

        /// <summary>
        /// 如果目录列表不存在 则创建目录
        /// </summary>
        /// <param name="dirs"></param>
        public static void CreateDirectorys(string[] dirs)
        {
            foreach (var dir in dirs)
            {
                CreateDirectory(dir);
            }
        }

        /// <summary>
        /// Create a entity based on an assembly
        /// </summary>
        /// <typeparam name="T">Entity type</typeparam>
        /// <param name="entity">T entity</param>
        /// <param name="collection">T Collection</param>
        /// <returns>T entity</returns>
        public static T PopulateEntity<T>(T entity, IDataReader collection) where T : new()
        {
            //Get type
            Type type = typeof(T);
            PropertyInfo[] pi = type.GetProperties();
            foreach (PropertyInfo item in pi)
            {
                //Set value for each property
                if (collection[item.Name] != null)
                {
                    bool isnull = DBNull.Value.Equals(collection[item.Name]);
                    if (!isnull)//数据库空值处理
                        item.SetValue(entity, Convert.ChangeType(collection[item.Name], item.PropertyType), null);
                }
            }
            return entity;
        }

        /// <summary>
        /// MD5加密位数枚举
        /// </summary>
        public enum MD5EncryptBit
        {
            bit16,
            bit32
        }

        /// <summary>
        /// 得到MD5加密结果
        /// </summary>
        /// <param name="Str">加密字符</param>
        /// <param name="EncryptBit">加密位数枚举16/32</param>
        /// <returns>MD5加密结果</returns>
        public static string GetMD5(string Str, MD5EncryptBit EncryptBit)
        {
            string result = string.Empty;

            switch (EncryptBit)
            {
                case MD5EncryptBit.bit16:
                    result = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Str, "MD5").Substring(8, 16);
                    break;
                case MD5EncryptBit.bit32:
                    result = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Str, "MD5");
                    break;
                default:
                    result = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Str, "MD5");
                    break;
            }

            return result;
        }

        /// <summary>
        /// 返回错误信息的xml
        /// </summary>
        /// <param name="errorMsg">错误信息</param>
        /// <returns></returns>
        public static string ErrorXml(string errorMsg)
        {
            var str = new StringBuilder();
            str.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            str.Append("<root><result>" + errorMsg + "</result></root>");
            return str.ToString();
        }

        /// <summary>
        /// 返回错误信息的xml
        /// </summary>
        /// <param name="errorCode">错误编码</param>
        /// <returns></returns>
        public static string ErrorXml(int errorCode)
        {
            var str = new StringBuilder();
            str.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            str.Append("<root><result>" + errorCode + "</result></root>");
            return str.ToString();
        }

        public static string ResultXml(int code, bool writeResult = true, int resultCode = 0)
        {
            var str = new StringBuilder();
            str.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            str.AppendLine("<root>");
            if (writeResult)
                str.AppendLine(string.Format("<result>{0}</result>", resultCode));
            str.AppendLine("<code>" + code.ToString() + "</code>");
            str.AppendLine("</root>");
            return str.ToString();
        }

        /// <summary>
        /// 读取webconfig文件AppSettings节点
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string AppSettings(string name)
        {
            return ConfigurationManager.AppSettings[name];
        }

        /// <summary>
        /// 自动补全数字
        /// </summary>
        /// <param name="number">增量的结束数字</param>
        /// <param name="seed">要取值的数字</param>
        /// <returns></returns>
        public static string AppendNumber(int number, int seed)
        {
            var str = new string('0', number.ToString().Length);
            return seed.ToString(str);
        }

        /// <summary>
        /// 当前请求实体id
        /// </summary>
        public static int EntityID { get { return HttpContext.Current.Request.QueryString["entityid"].ToInt32(); } }

        /// <summary>
        /// 当前请求菜单id
        /// </summary>
        public static int ModuleID { get { return HttpContext.Current.Request.QueryString["mid"].ToInt32(); } }

        /// <summary>
        /// 当前登录用户id
        /// </summary>
        public static int CurrentUserID { get { return HttpContext.Current.User.Identity.Name.Split('|')[1].ToInt32(); } }

        /// <summary>
        /// 当前登录用户名
        /// </summary>
        public static string CurrentUserName { get { return HttpContext.Current.User.Identity.Name.Split('|')[0]; } }

        /// <summary>
        /// 图片模板
        /// </summary>
        public static string ImgTemplate { get { return "<a href='{0}' target='_blank' title='单击查看大图'><img src='{0}' style='width:180px;height:120px' /></a>"; } }

        /// <summary>
        /// 订单id 用于在订单商品里获取 Url参数需名为orderid
        /// </summary>
        public static string OrderID { get { return HttpContext.Current.Request.QueryString["orderid"] ?? ""; } }


        /// <summary>
        /// 子级商品页面跳转路径
        /// </summary>
        public static string GoodsListUrl { get { return Method.GetHomeBaseUrl("List.aspx?orderid=" + Method.OrderID + "&mid=" + HttpContext.Current.Request.QueryString["mid"]); } }

        /// <summary>
        /// 返回list页面 保留当前页面的所有?传参查询
        /// </summary>
        public static string OriginalQueryUrl { get { return Method.GetHomeBaseUrl("List.aspx" + HttpContext.Current.Request.Url.Query); } }

        /// <summary>
        /// 是否调用php接口同步A平台数据 true调用 false不调用
        /// </summary>
        public static bool PhpPlatformASync { get { return AppSettings("PhpPlatformASync") == "true"; } }

        public static bool GetInOrNoteInterface(int GoodsTypeId, int Number)
        {
            if (GoodsTypeId < Number)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone">电话号码</param>
        /// <param name="msg">内容</param>
        public static string z_SendSMS(string phone, string msg)
        {
            string loginid = AppSettings("loginid");
            string userpass = AppSettings("userpass");
            if (loginid.IsEmpty() || userpass.IsEmpty() || phone.IsEmpty() || msg.IsEmpty())
            {
                throw new Exception("Parameter cannot be null.");
            }
            userpass = GetMD5(userpass, Function.Method.MD5EncryptBit.bit32).ToLower();
            //userpass = "21218cca77804d2ba1922c33e0151105";
            var strdata = string.Format("http://api.cq168.net/sendsms.php?loginid={0}&userpass={1}&content={2}&tels={3}&pdcode=1001", loginid, userpass, msg, phone);
            System.Net.WebClient client = new System.Net.WebClient();
            return client.UploadString(strdata, "");
        }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone">电话号码</param>
        /// <param name="msg">内容</param>
        public static void SendSMS(string phone, string msg)
        {
            var url = AppSettings("smstemplate");
            if (url.IsEmpty() || phone.IsEmpty() || msg.IsEmpty())
            {
                throw new Exception("Parameter cannot be null.");
            }
            var strdata = string.Format(url, phone, msg);
            WebClient client = new WebClient();
            client.UploadString(strdata, "");
        }

        public static Boolean NewSendSMS(string phone, string msg, out string Message)
        {
            Message = "";
            bool ok = true;
            try
            {
                var url = AppSettings("smstemplate");
                url += "?loginid={0}&userpass={1}&tels={2}&content={3}&pdcode=1001";
                string loginid = AppSettings("loginid");
                string userpass = AppSettings("userpass");
                if (loginid.IsEmpty() || userpass.IsEmpty() || phone.IsEmpty() || msg.IsEmpty())
                {
                    throw new Exception("Parameter cannot be null.");
                }
                userpass = GetMD5(userpass, Function.Method.MD5EncryptBit.bit32).ToLower();
                var strdata = string.Format(url, loginid, userpass, phone, msg);
                System.Net.WebClient client = new System.Net.WebClient();
                string replay = client.UploadString(strdata, "");
                string[] aa = GetTaoBaoIdList(replay);
                if (aa[0].Trim() != "-1")
                {
                    ok = false;
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                ok = false;
            }
            return ok;
        }
        public static string[] GetTaoBaoIdList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签//^mm_[0-9]{8}_[0-9]+_[0-9]$
            Regex regPid = new Regex(@"-[0-9]+", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串
            MatchCollection matches = regPid.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表
            foreach (Match match in matches)
                sUrlList[i++] = match.ToString();
            return sUrlList;
        }

        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="imgpath">要加水印的原图</param>
        /// <param name="filename">文件名</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置1=左上 2=中上 3=右上 4=左中  5=中中 6=右中 7=左下 8=右中 9=右下</param>
        /// <param name="quality">加水印后的质量0~100,数字越大质量越高</param>
        /// <param name="watermarkTransparency">水印图片的透明度1~10,数字越小越透明,10为不透明</param>
        public static void ImageWaterMarkPic(string imgpath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            var img = Image.FromFile(imgpath);
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                return;

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;
            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
                transparency = (watermarkTransparency / 10.0F);


            float[][] colorMatrixElements = {
                                                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
                case 1:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 2:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 3:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 4:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 5:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 6:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 7:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 8:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 9:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                    ici = codec;
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
                quality = 80;

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
                img.Save(filename, ici, encoderParams);
            else
                img.Save(filename);

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }

        public static string ResponseMyIP()
        {
            string str = null;
            try
            {
                //这个负责抓IP的页。第一步先抓取这个html页的全部内容
                string url = "http://www.ikaka.com/ip/index.asp";
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Credentials = CredentialCache.DefaultCredentials;
                Byte[] pageData = wc.DownloadData(url);
                string MyUrl = System.Text.Encoding.UTF8.GetString(pageData);
                //正则找到页面中的IP部分，并输出。
                Regex regex = new Regex(@"(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))");
                foreach (Match m in regex.Matches(MyUrl))
                {
                    str = m.ToString();
                }
            }
            catch (Exception)
            {
                str = "获取IP失败!";
            }
            return str;

        }
    }
}
